package lion.framework.core.web.views;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import lion.framework.core.conf.Config;
import lion.framework.core.conf.ConfigManager;
import lion.framework.core.web.anno.ViewType;
import lion.framework.core.web.request.Request;
import lion.framework.core.web.request.RequestModel;
import lion.json.Json;

/**
 * 将通过 {@link Request}.addModel('json',object)或 {@link HttpServletRequest}
 * .setAttribute("json",object) 设置的对象转为json字符串输出。
 * 如果请求中未设置json对像，则将Request转为Json输出
 * 
 * <pre>
 * time   2013 2013-5-14 下午04:15:14
 * mail   hl_0074@sina.com
 * </pre>
 *
 * @author lion
 */
@ViewType("json")
public class JSONView implements IView {

	public static final String VIEW_TYPE = "json";
	private String name;

	@Override
	public void render(HttpServletRequest request, HttpServletResponse response) throws Exception {

		// 设置为application/json后IE会认为是普通文件进行下载
		Config config = ConfigManager.getConfig("framework");
		response.setContentType("application/javascript;charset=" + config.getString("framework.sysencoding", "UTF-8"));
		response.setHeader("Cache-Control", "no-cache,no-store,must-revalidate,max-age=0,proxy-revalidate,no-transform,pre-check=0,post-check=0,private");
		response.setHeader("Pragma", "no-cache");
		response.setHeader("Expires", "0");

		Object json = request.getAttribute("json");
		if (json == null) {
			json = new RequestModel(request);
		}
		try {
			response.getWriter().write(Json.toJson(json));
		} catch (Exception e) {
			throw e;
		}
	}

	@Override
	public String getName() {

		return name;
	}

	@Override
	public String type() {

		return VIEW_TYPE;
	}

}
